<?php

class JobManager {	
	private $jobService;
	
	public function __construct() {
		$this->jobService = JobService::getInstance();		
	}
	
	public function getAllJobs($baseDate) {
		Yii::log('begin get all jobs from db', CLogger::LEVEL_INFO, SCHEDULER_LOG);
	
		$allFreqs = $this->jobService->getAllFreqencies();	
		if($allFreqs === false) {
			Yii::log('get all frequencies failed', CLogger::LEVEL_ERROR, SCHEDULER_LOG);
			return false;
		}
		$freqs = DateHelper::getFreqencyList($baseDate, $allFreqs);
		$allJobs = array();
		if(count($freqs) > 0) {
			$jobs = $this->jobService->getScheduleJobs($freqs);		
			if($jobs !== false) {				
				$allJobs = $this->createJobInstances($jobs);
            }
		}
		
        $oneTimeJobs = $this->jobService->getOneTimeJobs();
        if($oneTimeJobs !== false) {
            foreach($oneTimeJobs as $job) {
            	$this->jobService->editJobAttributes($job['job_id'], array('state'  =>  JobState::Done));
            }
            
            $allJobs = array_merge($allJobs, $this->createJobInstances($oneTimeJobs));
        }
		Yii::log('get all jobs succeed, total: ' . count($allJobs), CLogger::LEVEL_INFO, SCHEDULER_LOG);	
		return $allJobs;
	}
	
	private function createJobInstances($jobs) {		
		$jobInstances = array();
		if(!is_array($jobs)) {
			return $jobInstances;
		}
		
		foreach ($jobs as $job) {	
			$jobInstances[] = new BaseJob($job);
		}
		return $jobInstances;
	}
}
